package com.example.cc.mygit.view.userInfo.userProjects;

import com.example.cc.mygit.GitApplication;
import com.example.cc.mygit.model.Project;
import com.example.cc.mygit.model.User;
import com.example.cc.mygit.source.API;
import com.example.cc.mygit.view.project.ProjectContract;
import com.haibin.elegant.Response;
import com.haibin.elegant.call.CallBack;

import java.util.List;

/**
 * Created by cc on 2017/3/18.
 */

public class UserProjectsPresenter implements ProjectContract.Presenter {

    private String uid;
    private int mPage = 1;
    private final ProjectContract.View mView;
    private User mUser;

    private int itemSize;
    private String token;

    public UserProjectsPresenter(ProjectContract.View mView, User user) {

        this.mUser = user;
        this.uid = String.valueOf(user.getId());
        this.mView = mView;
        this.mView.setPresenter(this);
    }

    @Override
    public void onRefreshing() {
        if (mUser.getPrivateToken() != null)
            token = mUser.getPrivateToken();
        else
            token = "";
        API.getUserProjects(uid, 1, token, new CallBack<List<Project>>() {
            @Override
            public void onResponse(Response<List<Project>> response) {
                List<Project> items = response.getBody();
                if (items != null) {
                    mView.onRefreshSuccess(items);
                    mPage = 1;
                    ++mPage;
                }
                if (items.size() < 20) {
                    itemSize = items.size();
                }
                mView.onComplete();
            }

            @Override
            public void onFailure(Exception e) {
                mView.showNetWorkError();
                mView.onComplete();
            }
        });
    }

    @Override
    public void onLoadMore() {
        if (itemSize < 20) {
            mView.showNoMoreData();
            mView.showToastShort("没有更多的数据");
        } else {
            if (mUser.getPrivateToken() != null)
                token = mUser.getPrivateToken();
            else
                token = "";
            API.getUserProjects(uid, mPage, token, new CallBack<List<Project>>() {
                @Override
                public void onResponse(Response<List<Project>> response) {
                    List<Project> items = response.getBody();
                    if (items != null) {
                        mView.onLoadMoreSuccess(items);
                        if (items.size() < 20) {
                            mView.showNoMoreData();
                            --mPage;
                        }
                        mView.onComplete();
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    mView.showNetWorkError();
                    mView.onComplete();
                }
            });
        }
    }

    @Override
    public void start() {

    }
}
